package com.example.mediaservice.websocket;

import org.springframework.stereotype.Controller;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.sound.sampled.*;
import java.io.*;
import java.io.FileOutputStream;

@Controller
@ServerEndpoint("/page/audio")
public class SendAudio {
    public static final CopyOnWriteArraySet<SendAudio> sendAudioSessions = new CopyOnWriteArraySet<>();
    public Session session;
    private final String inputWavPath = "inputWavPath.wav";
    private final String outputPcmPath = "outputPcmPath.pcm";

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("onOpen");
        this.session = session;
        session.getBasicRemote().sendText("连接成功");
        sendAudioSessions.add(this);
    }

    @OnClose
    public void onClose() throws IOException {
        System.out.println("onClose");
        sendAudioSessions.remove(this);
        this.session.close();
    }

    public static void convertWavToPcm(String inputPath, String outputPath,
                                       int targetSampleRate, int targetBitDepth,
                                       int targetChannels) throws Exception {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(inputPath));
        // 获取原始音频格式
        AudioFormat sourceFormat = audioInputStream.getFormat();
        System.out.println("原始音频格式: " + sourceFormat);
        // 定义目标音频格式
        AudioFormat targetFormat = new AudioFormat(
                targetSampleRate,
                targetBitDepth,
                targetChannels,
                true,  // 有符号
                false  // 小端序
        );
        // 如果源格式与目标格式不同，则进行转换
        if (!sourceFormat.matches(targetFormat)) {
            System.out.println("需要进行格式转换...");
            audioInputStream = AudioSystem.getAudioInputStream(targetFormat, audioInputStream);
        }
        // 创建输出流
        try (OutputStream outputStream = Files.newOutputStream(Paths.get(outputPath))) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = audioInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
        audioInputStream.close();
    }

    @OnMessage(maxMessageSize=1024*1024)
    public void onMessage(byte[] wavData, Session session) throws Exception {
        Object[] arr = ReceiveAudio.receAudioSessions.toArray();
        // 写入数据
        try (FileOutputStream fos = new FileOutputStream(inputWavPath)) {
            fos.write(wavData);
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception();
        }
        // wav转pcm
        convertWavToPcm(inputWavPath, outputPcmPath, 16000, 16, 2);
        // 读取文件
        byte[] pcmData;
        try (FileInputStream fis = new FileInputStream(outputPcmPath);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }
            pcmData = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception();
        }
        // 转发
        ByteBuffer byteBuffer=ByteBuffer.allocate(pcmData.length);
        byteBuffer.put(pcmData);
        byteBuffer.flip();
        System.out.println("录音: " + byteBuffer.capacity());
        for(Object _item:arr) {
            ReceiveAudio item = (ReceiveAudio) _item;
            item.session.getBasicRemote().sendBinary(byteBuffer);
        }
    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        System.out.println("onError");
        error.printStackTrace();
        sendAudioSessions.remove(this);
        session.close();
    }

    public void sendMessage(ByteBuffer pcmData) throws IOException {
        this.session.getBasicRemote().sendBinary(pcmData);
    }
}
